<?php
// +----------------------------------------------------------------------
// | Description: 客户扩展设置
// +----------------------------------------------------------------------
// | Author:  Zl
// +----------------------------------------------------------------------
namespace app\crm\model;

use app\admin\model\ShopModel;
use app\admin\model\ShopOrderModel;
use app\shop\model\Goods;
use app\shop\model\Refund;
use think\facade\Db;
use app\admin\model\Common;
use think\Request;
use think\Validate;
use app\crm\validate\CustomerPrestockGoods as customerPrestockGoodsValidate;


class CustomerPrestockGoods extends Common
{
    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'customer_prestock_goods';
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $autoWriteTimestamp = true;

    //门店信息
    public function shop(){
        return $this->hasOne(ShopModel::class,'shop_id','shop_id');
    }
    //商品信息
    public function goods(){
        return $this->hasOne(Goods::class,'id','goods_id');
    }
    //出货单信息
    public function shopordergoods(){
        return $this->hasOne(ShopOrderGoods::class,'id','order_goods_id');
    }
    //顾客信息
    public function customer(){
        return $this->hasOne(Customer::class,'id','customer_id');
    }
    //预存货退出记录表
    public function shipmentlog(){
        return $this->hasMany(CustomerPrestockExit::class,'c_prestock_goods_id','id')->where('type',1)->where('is_cancel',1);
    }




    function is_integer_value($value) {
        return is_numeric($value) && floor($value) == $value;
    }


    //出货-预存货
    public function shipment($param){
        Db::startTrans();
        try {
            $validate = new customerPrestockGoodsValidate();
            if (!$validate->scene('create')->check($this->humpToUnderscore($param))) {
                throw new \Exception($validate->getError());
            }
            $id = $param['id'];
            $info = $this->where('id',$id)->lock(true)->find();
            if(empty($info)){
                throw new \Exception('预存货商品不存在');
            }

            $shop_id = $param['shop_id'];
            if($info['shop_id'] != $shop_id ){
                throw new \Exception('预存门店与开单门店不一致');
            }

            $max_num  = $info['num'];//当前预存最大数量
            $out_num = $param['num']; //出库数量
            if($max_num < $out_num){
                throw new \Exception('超出预存数量');
            }

            $operator_id = $param['operator_id']; //操作者
            $operate_time = time();//操作时间


            $num_diff = bcsub($max_num,$out_num,2);//剩余预存数量
            $info->num = $num_diff;
            $info->update_time = $operate_time;
            $res = $info->save();
            if(!$res){
                throw new \Exception('预存货商品库存修改失败');
            }

            $customer_data = Customer::where('id',$info['customer_id'])
                ->field('source_type_id,source_id,customer_name')
                ->find();

            $shop = ShopModel::where('shop_id',$shop_id)->find(); //门店名称

            $goods_price = bcmul($info['goods_price'],$out_num,2); //订单标准金额

            //预存时，生成的出货单商品信息
            $shop_order_goods = ShopOrderGoods::where('id',$info['order_goods_id'])->find();
            $cjyh_amount = $shop_order_goods['discount_amount'];  //冲减优惠金额
            //预存时，生成的出货单信息
            $shop_order = ShopOrderModel::where('id',$info['order_id'])->find();


            //订单总金额
            $total_amount = bcmul($shop_order_goods['pay_price'],$out_num,2);

            //单次消耗的本金
            $once_consume_bj = bcdiv($shop_order_goods['pay_amount'],$shop_order_goods['number'],2);
            //单次消耗的赠金
            $once_consume_zj = bcdiv($shop_order_goods['gift_amount'],$shop_order_goods['number'],2);
            //单次的冲减优惠金额
            $once_discount_amount  = bcdiv($shop_order_goods['discount_amount'],$shop_order_goods['number'],2);

            //消耗的本金
            $consume_bj = bcmul($once_consume_bj,$out_num,2);
            //消耗的赠金
            $consume_zj = bcmul($once_consume_zj,$out_num,2);
            //消耗的冲减优惠
            $discount_amount = bcmul($once_discount_amount,$out_num,2);


            // 生成出库单
            $data = [
                'uid'               => $info['customer_id'], // 客户
                'uid_source_type_id' => $customer_data['source_type_id'],
                'source_id'         => $customer_data['source_id'],
                'consignee'         => trim($customer_data['customer_name']), // 收货人
                'order_no'          => $this->getOrderNo(), // 订单号
                'sale_id'           => $shop_order['sale_id'], // 销售员id-为预存时的开单人
                'sale_name'         => $shop_order['sale_name'], // 销售员姓名 -同上
                'shop_id'           => $shop_id, // 门店id
                'shop_name'         => $shop['shop_name'], // 门店名称
                'operator_id'       => $operator_id,//制单员id
                'operator_name'     => $param['operator_name'],//制单员姓名
                'create_time'       => $operate_time, // 创建时间
                'deal_time'         => strtotime(date('Y-m-d')), // 成交日期
                'goods_price'       => $goods_price, // 订单标准金额
                'order_amount'      => bcadd($consume_bj,$consume_zj,2),//订单金额
                'total_amount'      => bcadd($consume_bj,$consume_zj,2), // 订单总金额
                'pay_amount'        => $consume_bj, // 实收本金
                'gift_amount'       => $consume_zj, // 实收赠金
                'discount_amount'   => 0, // 订单优惠金额
                'shop_transfer_amount' => 0, //实收店转
                'coupon_id'          =>  0, // 优惠券id
                'coupon_name'        => '', // 优惠券名称
                'description'        => '从客户预存货列表点击出库', // 订单描述
                'order_type'         => 2 , // 订单类型 1新单 2补单
                'project_type'       => 0 , // 项目分类
                'business_type'      => $shop_order_goods['data_business_type'] , // 业务类型 1项目 2疤痕 3青春痘 4护肤品
                'business_two_type'  => $shop_order_goods['data_business_two_type'],// 业务类型二级分类  1身体项目  2 皮肤项目
                'income_type'        =>  $shop_order['income_type'], // 收入类型 1 服务（各类疗程卡项及疗程卡项赠送产品）2 产品销售（单独付费购买产品）3 医美收入
                'sales_policy'       => '', // 销售政策编码
                'market_id'          => $shop['market_id'], // 市场id
                'market_name'        => $shop['market_name'], // 市场名称
                'sales_organization'       => $shop['market_kingdee_code'], // 销售组织编码
                'sales_name'         =>  $shop['market_name'], // 销售组织名称
                'settlement_organization'   => $shop['market_kingdee_code'], // 结算组织编码
                'settlement_name'       => $shop['market_name'], // 结算组织名称
                'order_experience'      => '' ,//订单是否有体验商品
                'delivery_name'       => $shop['shop_name'], // 发货部门名称
                'delivery_king'       => isset($shop['keycode']) ? $shop['keycode'] : '', // 发货部门编码
            ];
//                echo 222;die;
            $orderRes = ShopOrderModel::create($data);
            //生成服务卡项-生成订单-待定
            $order_id = $orderRes->id;
            $orderGoodsList =[];
            $orderGoodsList['data_business_type'] = $shop_order_goods['data_business_type'];
            $orderGoodsList['data_business_two_type'] = $shop_order_goods['data_business_two_type'];
            $orderGoodsList['order_id'] = $order_id;
            $orderGoodsList['create_time'] = $operate_time;
            $orderGoodsList['goods_id'] = $shop_order_goods['goods_id'];
            $orderGoodsList['goods_name'] = $shop_order_goods['goods_name'];
            $orderGoodsList['kingdee_code'] = $shop_order_goods['kingdee_code'];
            $orderGoodsList['goods_price'] =  $shop_order_goods['goods_price'];
            $orderGoodsList['pay_price'] = $shop_order_goods['pay_price'];
            $orderGoodsList['spec_name'] = $shop_order_goods['spec_name'];
            $orderGoodsList['unit_code'] = $shop_order_goods['unit_code'];
            $orderGoodsList['unit_name'] =  $shop_order_goods['unit_name'];
            $orderGoodsList['number'] = $out_num;
            $orderGoodsList['desc'] = '出商品预存货';
            $orderGoodsList['is_project'] = $shop_order_goods['is_project'];//是否服务 1 是 2否
            $orderGoodsList['category_id'] =  $shop_order_goods['category_id'];
            $orderGoodsList['is_coupon_goods'] = $shop_order_goods['is_coupon_goods'];//是否优惠券商品 0否 1是
            $orderGoodsList['project_type'] = $shop_order_goods['project_type'];//服务类型 1 按次 2按天
            $orderGoodsList['service_number'] = $shop_order_goods['service_number'];//服务次数
            $orderGoodsList['start_time']    = $shop_order_goods['start_time'];
            $orderGoodsList['end_time'] = $shop_order_goods['end_time'];
            $orderGoodsList['is_gift'] = $shop_order_goods['is_gift'];
            $orderGoodsList['house_code'] = $shop_order_goods['house_code'];  //仓库编码
            $orderGoodsList['coupon_type'] = 0;//优惠券类型
            $orderGoodsList['house_code_name'] = $shop_order_goods['house_code_name']; //仓库名称
            $orderGoodsList['goods_alias_name'] = $shop_order_goods['goods_alias_name'];

            $orderGoodsList['prestock_type'] = 3;
            $orderGoodsList['takeout_stock_num'] = $out_num;
            $orderGoodsList['gift_amount'] = $data['gift_amount'];
            $orderGoodsList['pay_amount'] = $data['pay_amount'];
            $orderGoodsList['shop_transfer_amount'] = $data['shop_transfer_amount'];

            $shopOrderGoodsRes  = ShopOrderGoods::create($orderGoodsList);
            if(!$shopOrderGoodsRes){
                throw new \Exception('生成订单失败，请稍后重试！');
            }

            if($cjyh_amount != 0 ){
                $cjyh_goods = ShopGoods::where('kingdee_code','101.12.098')->cache(true)->find();//冲减优惠
                $orderGoodsList = [];
                $orderGoodsList['pay_amount'] = abs($discount_amount);
                $orderGoodsList['gift_amount'] = 0;
                $orderGoodsList['shop_transfer_amount'] = 0;
                $orderGoodsList['order_id'] = $order_id;
                $orderGoodsList['create_time'] = time();
                $orderGoodsList['goods_id'] = $cjyh_goods['id'];
                $orderGoodsList['goods_name'] = $cjyh_goods['name'];
                $orderGoodsList['kingdee_code'] = $cjyh_goods['kingdee_code'];
                $orderGoodsList['goods_price'] = $cjyh_goods['goods_price'];
                $orderGoodsList['pay_price'] = abs($discount_amount); //售卖价格
                $orderGoodsList['spec_name'] = $cjyh_goods['spec_name'];
                $orderGoodsList['unit_code'] = $cjyh_goods['unit_code'];
                $orderGoodsList['unit_name'] = $cjyh_goods['unit_name'];
                $orderGoodsList['number'] = $discount_amount < 0 ?-1:1;
                $orderGoodsList['desc'] = '预存货出库-产出出库单明细-冲减优惠';
                $orderGoodsList['is_project'] = 2;//是否服务 1 是 2否
                $orderGoodsList['category_id'] = $cjyh_goods['category_id'];
                $orderGoodsList['is_coupon_goods'] = 0;//是否优惠券商品 0否 1是
                $orderGoodsList['project_type'] = 0;//服务类型 1 按次 2按天
                $orderGoodsList['service_number'] = 0;//服务次数
                $orderGoodsList['is_gift'] = 0;  //是否为赠品
                $orderGoodsList['house_code'] =  $shop_order_goods['house_code'];
                $orderGoodsList['coupon_type'] = 0;//优惠券类型
                $orderGoodsList['house_code_name'] = $shop_order_goods['house_code_name'];
                $orderGoodsList['goods_alias_name'] = $shop_order_goods['goods_alias_name'];
                $orderGoodsList['prestock_type'] = 1; //预存货类型
                $orderGoodsList['takeout_stock_num'] = 1;  //出货数量
                $orderGoodsList['data_business_type'] = $shop_order_goods['data_business_type'];  //业务类型
                $orderGoodsList['data_business_two_type'] = 0;  //业务类型
                $orderGoodsList['discount_amount'] = 0;  //折扣金额
                $orderGoodsList['after_discount_amount'] = 0;  //优惠后金额
                $order_goods_res = ShopOrderGoods::create($orderGoodsList);
            }


            $shop_order_goods_id =$shopOrderGoodsRes->id;
            //生成商品出货记录
            $insert = [
                'operator_id'=>$operator_id,
                'create_time'=>$operate_time,
                'shop_order_id'=>$order_id,
                'shop_order_goods_id'=>$shop_order_goods_id,
                'c_prestock_goods_id'=>$id,
                'shop_id'=>$shop_id,
                'customer_id'=>$info['customer_id'],
                'type'=>1,
                'remark'=>$param['reason'],
                'num'=>$out_num,
            ];
            $res = CustomerPrestockExit::create($insert);
            if(!$res){
                throw new \Exception('网络错误，请稍后重试');
            }

            // 金蝶推送云星空订单 -出库单
            $refundModel = new Refund();
            $refundModel->sendYxk($info['customer_id'],5,$order_id);

            Db::commit();
            return true;


        }catch (\Exception $e){
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
    }
    //生成订单号
    public function getOrderNo()
    {
        $order_sn = null;
        // 保证不会有重复订单号存在
        while(true){
            $order_sn = date('YmdHis').rand(1000,9999); // 订单编号
            $order_sn_count = DB::name('shop_order')->where('order_no', $order_sn)->count();
            if($order_sn_count == 0) break;
        }
        return $order_sn;
    }

    //商品-预存货列表
    public function prestockGoodslist($param){
        $customer_id = $param['customer_id'];
        $good_id = $param['good_id'];
        $shop_id = $param['shop_id'];
        $where = [
            ['goods_id','=',$good_id],
            ['shop_id','=',$shop_id],
            ['customer_id','=',$customer_id],
            ['num','>',0],
            ['is_cancel','=',0]
        ];
        $goods_data = $this->with([
            'shopordergoods'=>function($query)use($where){
                $query->field('id,goods_name,goods_alias_name,spec_name,unit_name,is_project,project_type,goods_price,pay_price,takeout_stock_num,gift_amount,pay_amount,number');
            }
        ])->where($where)->select()->toArray();
        if(!empty($goods_data)){
            $time = time();
            $goods = [];
            foreach($goods_data as $k=>&$v) {
                $goods_name =  $goods_price = $pay_price  = '数据丢失';
                $shipment_num =  $takeout_stock_num = $pay_price =  0 ;
                if(!empty($v['shopordergoods'])){
                    $goods_name = $v['shopordergoods']['goods_name'];
                    $goods_price = $v['shopordergoods']['goods_price'];
                    $spec_name =$v['shopordergoods']['spec_name'];
                    $order_goods_amount = bcadd($v['shopordergoods']['gift_amount'],$v['shopordergoods']['pay_amount'],2);
                    $pay_price = bcdiv($order_goods_amount,$v['shopordergoods']['number'],2);
                    $takeout_stock_num = $v['shopordergoods']['takeout_stock_num'];
                }

                if($v['service_type'] == 2 && $v['goods_type'] == 2){
                    if($v['project_begin_time'] <= $time && $time <= $v['project_end_time']){
                        $return_goods =[
                            'c_prestock_goods_id'=>$v['id'],
                            'goods_name'=>$goods_name,
                            'goods_price'=>$goods_price,
                            'project_type'=>$v['service_type'],
                            'is_project'=>$v['goods_type'],
                            'service_num' =>$v['service_num'],
                            'max_num'=>$v['num'],
                            'project_begin_time'=>!empty($v['project_begin_time']) ? date('Y-m-d',$v['project_begin_time']):'',
                            'project_end_time'=>!empty($v['project_end_time']) ? date('Y-m-d',$v['project_end_time']):'',
                            'spec_name'=>$spec_name,
                            'pay_price'=>$pay_price,
                            'shipment_num'=>$shipment_num,
                            'littleCount' => bcmul($pay_price,$takeout_stock_num,2),
                            'prestock_time' => $v['create_time']
                        ];
                    }
                }else{
                    $return_goods =[
                        'c_prestock_goods_id'=>$v['id'],
                        'goods_name'=>$goods_name,
                        'goods_price'=>$goods_price,
                        'project_type'=>$v['service_type'],
                        'is_project'=>$v['goods_type'],
                        'service_num' =>$v['service_num'],
                        'max_num'=>$v['num'],
                        'project_begin_time'=>!empty($v['project_begin_time']) ? date('Y-m-d',$v['project_begin_time']):'',
                        'project_end_time'=>!empty($v['project_end_time']) ? date('Y-m-d',$v['project_end_time']):'',
                        'spec_name'=>$spec_name,
                        'pay_price'=>$pay_price,
                        'shipment_num'=>$shipment_num,
                        'littleCount' => bcmul($pay_price,$takeout_stock_num,2),
                        'prestock_time' => $v['create_time']

                    ];
                }
                array_push($goods,$return_goods);
            }
            return $goods;
        }else{
            throw new \Exception('暂无预存商品');
        }

    }

    //商品-单个商品预存货验证
    public function prostockShipmentVerify($param){
        $goods = $param['prestock_goods']??[];
        if(!empty($goods)){
            $sum_num = $sum_price = 0.00;
            $all_goods_price = [];
            $ids =  array_column($goods,'c_prestock_goods_id');
            $data = $this->whereIn('id',$ids)->with([
                'shopordergoods'=>function($query)use($all_goods_price){
                    $query->field('id,pay_price');
                }
            ])->field('id,num as max_num,order_goods_id')->select()->toArray();
            $data = array_column($data,null,'id');

            foreach($goods as $k=>$v){
//                if($v['shipment_num'] <=0){
////                    throw new \Exception($v['goods_name'].'-出货数量需大于0');
//                }
                $sum_num = $sum_num + $v['shipment_num'];//出货总量
                if(isset($data[$v['c_prestock_goods_id']])){
                    $max_num = $data[$v['c_prestock_goods_id']]['max_num'];
                    if($v['shipment_num'] > $max_num ){
                        throw new \Exception($v['goods_name'].'-超出预存商品数量');
                    }
                    array_push($all_goods_price,bcmul($v['shipment_num'],$data[$v['c_prestock_goods_id']]['shopordergoods']['pay_price'],2));
                }else{
                    throw new \Exception('商品不合法');
                }
            }

            $sum_price = empty($all_goods_price)?0:array_sum($all_goods_price); //销售总额
            return ['num'=>bcadd(0,$sum_num,2),'sum_price'=>bcadd(0,$sum_price,2)];
        }else{
            throw new \Exception('暂无商品');
        }
    }


    //单个预存货明细
    public function prestockGoodslistDetail($param){
        $paging['page']  = isset($param['page']) && intval($param['page']) ? intval($param['page']) : 1;
        $paging['limit'] = isset($param['limit']) && intval($param['limit']) ? intval($param['limit']) : 15;

        $id = $param['id']??0;

        $prestockGoods = DB::name('customer_prestock_goods')->where('id',$id)->find();
        if(empty($prestockGoods)){
            throw new \Exception('预存货不存在');
        }


        $map = [
            ['c_prestock_goods_id','=',$id],
            ['is_cancel','=',1]
        ];

        $start_time = $param['start_time']??'';
        $end_time = $param['end_time']??'';
        if(!empty($start_time) && !empty($end_time)){
            array_push($map,['deal_time',"between","$start_time,$end_time"]);
        }

        $goodsList = CustomerPrestockExit::with([
            'shop'=>function($query)use($map){
                $query->field('shop_id,shop_name,market_name');
            },
            'customer'=>function($query)use($map){
                $query->field('id,customer_name');
            },
            'operator'=>function($query)use($map){
                $query->field('id,realname');
            }
        ]);
        $count = $goodsList->where($map)->count();
        if($count>0){
            $goodsList = $goodsList->where($map)
                ->order('id','desc')->select()
                ->toArray();

            foreach($goodsList as $k=>&$v){
                $v['shop_name'] = !empty($v['shop'])?$v['shop']['shopName']:'';
                $v['customer_name'] = !empty($v['customer'])?$v['customer']['customer_name']:'';
                $v['operator_name'] = !empty($v['operator'])?$v['operator']['realname']:'';
                if($v['type'] ==1){
                    //出货
                    $orderGoodsList = DB::name('shop_order_goods')->where('id',$v['shop_order_goods_id'])->field('goods_name,kingdee_code,pay_price,goods_price')->find();
                    $v['goods_name'] = !empty($orderGoodsList)?$orderGoodsList['goods_name']:'';
                    $v['goods_code'] = !empty($orderGoodsList)?$orderGoodsList['kingdee_code']:'';
                    $v['price'] = !empty($orderGoodsList)?$orderGoodsList['pay_price']:0.00;
                    $v['goods_price'] = !empty($orderGoodsList)?$orderGoodsList['goods_price']:0.00;
                }else{
                    $orderGoodsList = DB::name('shop_refund_order_goods')
                        ->where('id',$v['shop_order_goods_id'])
                        ->field('goods_name,kingdee_code,refund_principal_price,gift_price,shop_transfer_price,pay_price')->find();

                    $v['goods_name'] = !empty($orderGoodsList)?$orderGoodsList['goods_name']:'';
                    $v['goods_code'] = !empty($orderGoodsList)?$orderGoodsList['kingdee_code']:'';
                    $bj = !empty($orderGoodsList)?$orderGoodsList['refund_principal_price']:0.00;
                    $zj = !empty($orderGoodsList)?$orderGoodsList['gift_price']:0.00;
                    $dz = !empty($orderGoodsList)?$orderGoodsList['shop_transfer_price']:0.00;
                    $bj_zj_dz =bcadd(bcadd($bj,$zj,2),$dz,2);
                    $v['price'] = $bj_zj_dz;
                    $v['goods_price'] = !empty($orderGoodsList)?$orderGoodsList['pay_price']:0.00;
                }


                $v['type']  = $v['type'] == 1?'出货':'退货';
                $v['amount_sum'] = bcmul($v['price'],$v['num'],2);
            }
        }
        $data              = [];
        $data['list']      = $goodsList ?? [];
        $data['dataCount'] = $count ?? 0;
        return $data;
    }

    //明细预存货明细
    public function shopPrestockList($param){
        $paging['page']  = isset($param['page']) && intval($param['page']) ? intval($param['page']) : 1;
        $paging['limit'] = isset($param['limit']) && intval($param['limit']) ? intval($param['limit']) : 15;
        $start_time =  isset($param['start_time'])  ? strtotime($param['start_time']) : '';
        $end_time =  isset($param['end_time'])  ? strtotime($param['end_time']." 23:59:59") : '';
        $shop_name =  isset($param['shop_name'])  ? $param['shop_name'] : '';
        $consignee =  isset($param['consignee'])  ? $param['consignee'] : '';
        $goods_name =  isset($param['goods_name'])  ? $param['goods_name'] : '';
        $shopIds= $param['shopIds'] ?? '';
        $map = [
            ['is_cancel','=',0]
        ];

        $take_where= $preGoodsWhere = [];
        $whereExit = [];
        if(!empty($consignee)){
            $customer_ids = DB::name('customer')->where('customer_name','like',$consignee,"%")->column('id');
            array_push($map, ['customer_id','in',$customer_ids]);

            array_push($take_where, ['a.uid','in',$customer_ids]);
            array_push($preGoodsWhere, ['customer_id','in',$customer_ids]);
            array_push($whereExit, ['b.customer_id','in',$customer_ids]);
        }

        if(!empty($shop_name)){
            $shop_name_ids = DB::name('shop')->where('status',1)->where('shop_name','like',"%".$shop_name."%")->column('shop_id');
            array_push($map, ['shop_id','in',$shop_name_ids]);
            array_push($take_where, ['a.shop_id','in',$shop_name_ids]);
            array_push($preGoodsWhere, ['shop_id','in',$shop_name_ids]);
            array_push($whereExit, ['b.shop_id','in',$shop_name_ids]);

        }
        if(!empty($shopIds)){
            array_push($map,  ['shop_id','in',$shopIds]);
            array_push($take_where, ['a.shop_id','in',$shopIds]);
            array_push($preGoodsWhere, ['shop_id','in',$shopIds]);
            array_push($whereExit, ['b.shop_id','in',$shopIds]);
        }
        if(!empty($shop_id)){
            array_push($map, ['shop_id','=',$shop_id]);
            array_push($take_where, ['a.shop_id','=',$shop_id]);
            array_push($preGoodsWhere, ['shop_id','=',$shop_id]);
            array_push($whereExit, ['b.shop_id','=',$shop_id]);
        }
        if(!empty($goods_name)){
            $goods_id = DB::name('shop_goods')->where('name',"like",$goods_name."%")->column('id');
            array_push($map, ['goods_id','in',$goods_id]);
            array_push($take_where, ['b.goods_id','in',$goods_id]);
            array_push($preGoodsWhere, ['goods_id','in',$goods_id]);
            array_push($whereExit, ['b.goods_id','in',$goods_id]);
        }
        $goodsListQuery = CustomerPrestockGoods::where($map);
        $count = $goodsListQuery->count();
        if($count>0){
            $goodsList = $goodsListQuery->with([
                'shop'=>function($query)use($map){
                    $query->field('shop_id,shop_name,market_name');
                },
                'shopordergoods'=>function($query)use($map){
                    $query->field('id,goods_name,kingdee_code,spec_name,pay_price,number,prestock_type,takeout_stock_num,goods_price,data_business_type');
                },
                'customer'=>function($query)use($map){
                    $query->field('id,customer_name,king_no');
                },
            ])->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])
                ->order('id','desc')->select()
                ->toArray();

            $data_business_type = [
                1=>'疤痕', 2=>'项目', 3=>'青春痘', 4=>'护肤品', 0=>'无'
            ];
            $exitWhere = [
                ['type','=',1],
                ['is_cancel','=',1],
            ];
            if(!empty($start_time) && !empty($end_time)){
                array_push($exitWhere, ['deal_time','between',"$start_time,$end_time"]);
            }

            foreach($goodsList as $k=>&$v){
                $v['customer_name'] = !empty($v['customer'])?$v['customer']['customer_name']:'';
                $v['customer_code'] = !empty($v['customer'])?$v['customer']['king_no']:'';
                $v['goods_name'] = !empty($v['shopordergoods'])?$v['shopordergoods']['goods_name']:'';
                $v['goods_code'] = !empty($v['shopordergoods'])?$v['shopordergoods']['kingdee_code']:'';
                $v['spec_name'] = !empty($v['shopordergoods'])?$v['shopordergoods']['spec_name']:''; //规格
                $v['goods_price'] = !empty($v['shopordergoods'])?$v['shopordergoods']['goods_price']:0.00; //商品标准价格
                $v['pay_price'] = !empty($v['shopordergoods'])?$v['shopordergoods']['pay_price']:0.00; //商品销售单价
                $v['deal_time'] = $v['deal_time']>0?date('Y-m-d',$v['deal_time']):''; //预存时间

                $v['takeout_stock_num'] = !empty($v['shopordergoods'])?$v['shopordergoods']['takeout_stock_num']:0.00; //存货数量
                $v['sales_amount'] = bcmul($v['pay_price'],$v['shopordergoods']['number'],2); //销售金额
                $v['residual_shipment_num'] = $v['num']; //剩余存货数量

                $chukushuliang =  DB::name('customer_prestock_exit')->where($exitWhere)->where('c_prestock_goods_id',$v['id'])->sum('num');
                $v['shipment_num'] = $chukushuliang;
                $v['shipment_amount'] =bcmul($chukushuliang, $v['pay_price'],2);
                $v['residual_sales_amount'] = bcmul($v['num'],$v['pay_price'],2);
                $v['business_type'] = !empty($v['shopordergoods'])?$data_business_type[$v['shopordergoods']['data_business_type']]:'';
                $v['shop_name'] = !empty($v['shop'])?$v['shop']['shopName']:'';
                $v['market_name'] = !empty($v['shop'])?$v['shop']['marketName']:'';
            }

            $public_where =[
                ['a.status','=',2],
                ['b.prestock_type','=',2]
            ];

            //预存总数-预存总金额
            $takeout_stock_num = ShopOrderModel::alias('a')
                ->leftjoin('shop_order_goods b','a.id=b.order_id')
                ->where($public_where)->where($take_where)
                ->field('sum(b.takeout_stock_num) as num,sum(b.takeout_stock_num * b.pay_price) as sale_total')
                ->find();

            //剩余预存数-剩余总销售额
            $preGoods = CustomerPrestockGoods::where(function($query)use($public_where,$preGoodsWhere){
                $query->where('is_cancel',0);
                $query->where($preGoodsWhere);
            })->field('sum(num) as sum_total,sum(num * goods_price) as sale_total')->find()->toArray();

            //出货数量-出货金额
            $preGoodsExit = CustomerPrestockGoods::alias('a')
                ->leftjoin('customer_prestock_exit b','a.id=b.c_prestock_goods_id')
                ->where(function($query)use($public_where,$whereExit){
                    $query->where($whereExit);
                    $query->where('b.type',1);
                    $query->where('b.is_cancel',1);
                })->field('sum(b.num) as sum_total,sum(b.num * a.goods_price) as sale_total')
                ->find();

            $total = [
                'customer_name'=>'合计',
                'takeout_stock_num'=>$takeout_stock_num['num'], //存货数量
                'sales_amount'=>bcadd(0,$takeout_stock_num['sale_total'],2), //销售金额
                'shipment_num'=>$preGoodsExit['sum_total']??0,  //出货数量
                'shipment_amount'=>bcadd(0,$preGoodsExit['sale_total'],2), //出货金额
                'residual_shipment_num'=>$preGoods['sum_total']??0, //剩余数量
                'residual_sales_amount'=>bcadd(0,$preGoods['sale_total'],2),//剩余销售总额
            ];
            array_push($goodsList,$total);
        }

        $data              = [];
        $data['list']      = $goodsList ?? [];
        $data['dataCount'] = $count ?? 0;
        return $data;
    }

    //预存货明细-导出
    public function preListExit($param){

        $start_time =  isset($param['start_time'])  ? strtotime($param['start_time']) : '';
        $end_time =  isset($param['end_time'])  ? strtotime($param['end_time']." 23:59:59") : '';
        $shop_name =  isset($param['shop_name'])  ? $param['shop_name'] : '';//门店名称
        $consignee =  isset($param['consignee'])  ? $param['consignee'] : '';//客户姓名
        $goods_name =  isset($param['goods_name'])  ? $param['goods_name'] : '';//商品名称
        $shopIds= $param['shopIds'] ?? '';
        $map = [
            ['is_cancel','=',0]
        ];
        $where=[];
        if(!empty($consignee)){
            $customer_ids = DB::name('customer')->where('customer_name','like',$consignee,"%")->column('id');
            array_push($map, ['customer_id','in',$customer_ids]);
        }

        if(!empty($shop_name)){
            $shop_name_ids = DB::name('shop')->where('status',1)->where('shop_name','like',"%".$shop_name."%")->column('shop_id');
            array_push($map, ['shop_id','in',$shop_name_ids]);

        }
        if(!empty($shopIds)){
            array_push($map,  ['shop_id','in',$shopIds]);
        }
        if(!empty($shop_id)){
            array_push($map, ['shop_id','=',$shop_id]);
        }
        if(!empty($goods_name)){
            $goods_id = DB::name('shop_goods')->where('name',"like",$goods_name."%")->column('id');
            array_push($map, ['goods_id','in',$goods_id]);
        }

        $goodsListQuery = CustomerPrestockGoods::where($map);
        $goodsList = $goodsListQuery->with([
            'shop'=>function($query)use($map){
                $query->field('shop_id,shop_name,market_name');
            },
            'shopordergoods'=>function($query)use($map){
                $query->field('id,goods_name,kingdee_code,spec_name,pay_price,number,prestock_type,takeout_stock_num,goods_price,data_business_type');
            },
            'customer'=>function($query)use($map){
                $query->field('id,customer_name,king_no');
            },
        ])
            ->order('id','desc')->select()
            ->toArray();
        if(!empty($goodsList)){
            $data_business_type = [
                1=>'疤痕', 2=>'项目', 3=>'青春痘', 4=>'护肤品', 0=>'无'
            ];
            $exitWhere = [
                ['type','=',1],
                ['is_cancel','=',1],
            ];
            if(!empty($start_time) && !empty($end_time)){
                array_push($exitWhere, ['deal_time','between',"$start_time,$end_time"]);
            }
            foreach($goodsList as $k=>&$v){
                $v['customer_name'] = !empty($v['customer'])?$v['customer']['customer_name']:'';
                $v['customer_code'] = !empty($v['customer'])?$v['customer']['king_no']:'';
                $v['goods_name'] = !empty($v['shopordergoods'])?$v['shopordergoods']['goods_name']:'';
                $v['goods_code'] = !empty($v['shopordergoods'])?$v['shopordergoods']['kingdee_code']:'';
                $v['spec_name'] = !empty($v['shopordergoods'])?$v['shopordergoods']['spec_name']:''; //规格
                $v['goods_price'] = !empty($v['shopordergoods'])?$v['shopordergoods']['goods_price']:0.00; //商品标准价格
                $v['pay_price'] = !empty($v['shopordergoods'])?$v['shopordergoods']['pay_price']:0.00; //商品销售单价

                $v['takeout_stock_num'] = !empty($v['shopordergoods'])?$v['shopordergoods']['takeout_stock_num']:0.00; //存货数量
                $v['sales_amount'] = bcmul($v['pay_price'],$v['shopordergoods']['number'],2); //销售金额

                $v['residual_shipment_num'] = $v['num']; //剩余存货数量

                $chukushuliang =  DB::name('customer_prestock_exit')->where($exitWhere)->where('c_prestock_goods_id',$v['id'])->sum('num');

                $v['shipment_num'] = $chukushuliang;
                $v['shipment_amount'] =bcmul($chukushuliang, $v['pay_price'],2);

                $v['residual_sales_amount'] = bcmul($v['num'],$v['pay_price'],2);

                $v['business_type'] = !empty($v['shopordergoods'])?$data_business_type[$v['shopordergoods']['data_business_type']]:'';
                $v['shop_name'] = !empty($v['shop'])?$v['shop']['shopName']:'';
                $v['market_name'] = !empty($v['shop'])?$v['shop']['marketName']:'';
                $v['deal_time'] = date('Y-m-d',$v['deal_time']);
            }
        }
        $data              = [];
        $data['list']      = $goodsList ?? [];
        return $data;
    }


    //门店商品预存货
    public function shopPrestockGoodsList($param){
        $paging['page']  = isset($param['page']) && intval($param['page']) ? intval($param['page']) : 1;
        $paging['limit'] = isset($param['limit']) && intval($param['limit']) ? intval($param['limit']) : 15;

        $map = $where = [];

        $shopIds= $param['shopIds'] ?? '';
        if(!empty($shopIds)){
            array_push($map,  ['shop_id','in',$shopIds]);
            array_push($where,  ['a.shop_id','in',$shopIds]);
        }

        $shop_name = $param['shop_name'] ?? '';
        if(!empty($shop_name)){
            $shop_name_ids = DB::name('shop')->where('status',1)->where('shop_name','like',"%".$shop_name."%")->column('shop_id');

            array_push($map,['shop_id','in',$shop_name_ids]);
            array_push($where,  ['a.shop_id','in',$shop_name_ids]);
        }

        $goods_name = isset($param['goods_name'])  ? $param['goods_name'] : '';
        if(!empty($goods_name)){
            $goods_ids =ShopGoods::where('name','like','%'.$goods_name.'%')->column('id');
            array_push($map,['goods_id','in',$goods_ids]);

        }

        array_push($map,['is_cancel','=',0]);

        $prestock_count = CustomerPrestockGoods::where($map)
            ->field('sum(num) as num,goods_id')
            ->group('goods_id')
            ->having('num>0')
            ->count();

        if(!empty($prestock_count)){
            $list = CustomerPrestockGoods::where($map)
                ->field('sum(num) as num,goods_id')
                ->group('goods_id')
                ->having('num>0')
                ->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])
                ->select()->toArray(); //最后剩余次数

            $goodsids =array_column($list,'goods_id');
            $goods = ShopGoods::whereIn('id',$goodsids)->column('name,kingdee_code','id');

            array_push($where,['prestock_type','=',2]);
            array_push($where,['b.goods_id','in',$goodsids]);
            array_push($where,['a.status','=',2]);
            $prestock_list = ShopOrderModel::alias('a')
                ->leftjoin('shop_order_goods b','a.id=b.order_id')
                ->where($where)->group('b.goods_id')->column('sum(b.takeout_stock_num) as num,b.goods_id','goods_id');

            foreach($list as $k=>&$v){
                $v['id'] = $v['goods_id'];
                $v['goods_name'] = isset($goods[$v['goods_id']]) ?$goods[$v['goods_id']]['name'] :"";
                $v['kingdee_code'] = isset($goods[$v['goods_id']]) ?$goods[$v['goods_id']]['kingdee_code'] :"";
                $v['ultimately_surplus_num'] = $v['num'];
                $v['prestock_num'] = isset($prestock_list[$v['goods_id']])?$prestock_list[$v['goods_id']]['num']:0;
            }
        }

        $data              = [];
        $data['list']      = $list ?? [];
        $data['dataCount'] = $prestock_count ?? 0;
        return $data;
    }
    //门店商品预存货-预存明细
    public function shopPrestockGoodsDateil($param){

        $paging['page']  = isset($param['page']) && intval($param['page']) ? intval($param['page']) : 1;
        $paging['limit'] = isset($param['limit']) && intval($param['limit']) ? intval($param['limit']) : 15;

        $start_time = isset($param['start_time']) ? $param['start_time'] : '';
        $end_time = isset($param['end_time']) ? $param['end_time'] : '';


        $id = isset($param['id'])  ? intval($param['id']) : 0;
        $shopIds = isset($param['shopIds'])  ? $param['shopIds'] : '';


        $map=[
            ['b.goods_id','=',$id],
            ['a.status','=',2],
            ['b.prestock_type','=',2]
        ];

        if(!empty($start_time) && !empty($end_time)){
            $start_time = strtotime($start_time);
            $end_time = strtotime($end_time." 23:59:59");
            array_push($map,['a.deal_time','between',"$start_time,$end_time"]);
        }
        if(!empty($shopIds)){
            array_push($map,['a.shop_id','in',$shopIds]);
        }
        if(!empty($shop_id)){
            array_push($map,['a.shop_id','=',$shopIds]);
        }

        $shop_name = isset($param['shop_name']) && $param['shop_name'] ? trim($param['shop_name']) : ''; // 门店名称
        if(!empty($shop_name)){
            $shopids = DB::name('shop')->where('shop_name','like',"%".$shop_name."%")->column('shop_id');
            if(!empty($shopids)){
                array_push($map,['a.shop_id','in',$shopids]);
            }
        }



        $prestock_log_count = ShopOrderModel::alias('a')
            ->rightjoin('shop_order_goods b','a.id=b.order_id')
            ->where($map)->field('b.takeout_stock_num,b.goods_id,a.uid,a.shop_id,a.deal_time')->count();


        if($prestock_log_count>0){
            $prestock_log = ShopOrderModel::alias('a')
                ->leftjoin('shop_order_goods b','a.id=b.order_id')
                ->where($map)->field('b.takeout_stock_num,b.goods_id,a.uid,a.shop_id,a.deal_time,b.id')
                ->page($param['page'], $param['limit'])
                ->select()->toArray();


            $shop_order_goods_id = array_column($prestock_log,'id');
            $uid = array_column($prestock_log,'uid');
            $shop_id = array_column($prestock_log,'shopId');

            $customer = DB::name('customer')->whereIn('id',$uid)->column('customer_name,telephone','id');
            $shop = DB::name('shop')->whereIn('shop_id',$shop_id)->column('shop_name','shop_id');
            $prestock_goods_list = DB::name('customer_prestock_goods')->whereIn('order_goods_id',$shop_order_goods_id)->column('num','order_goods_id');
            $goods_name = DB::name('shop_goods')->where('id',$id)->value('name');
            foreach($prestock_log as $k=>&$v){
                $v['goods_name'] = $goods_name;
                $v['customer_name'] = isset($customer[$v['uid']])?$customer[$v['uid']]['customer_name'] :'';
                $v['shop_name'] = isset($shop[$v['shopId']]) ? $shop[$v['shopId']]:'';
                $v['prestock_num'] = isset($prestock_goods_list[$v['id']])?$prestock_goods_list[$v['id']]:0;
                $v['deal_times'] = date('Y-m-d',$v['dealTime']);
            }
        }
        $data              = [];
        $data['list']      = $prestock_log ?? [];
        $data['dataCount'] = $prestock_log_count ?? 0;
        return $data;
    }

    //门店商品预存货-预存明细
    public function refundOutPrestockDateil($param){
        $paging['page']  = isset($param['page']) && intval($param['page']) ? intval($param['page']) : 1;
        $paging['limit'] = isset($param['limit']) && intval($param['limit']) ? intval($param['limit']) : 15;

        $start_time = isset($param['start_time']) ? $param['start_time'] : '';
        $end_time = isset($param['end_time']) ? $param['end_time'] : '';

        $id = isset($param['id'])  ? intval($param['id']) : 0;
        $shopIds = isset($param['shopIds'])  ? $param['shopIds'] : '';
        $shop_id  =  isset($param['shop_id'])  ? $param['shop_id'] : '';
        $shop_name = isset($param['shop_name']) && $param['shop_name'] ? trim($param['shop_name']) : ''; // 门店名称

        $map=[
            ['goods_id','=',$id],
            ['is_cancel','=',1],
        ];

        if(!empty($start_time) && !empty($end_time)){
            $start_time = strtotime($start_time);
            $end_time = strtotime($end_time." 23:59:59");
            array_push($map,['deal_time','between',"$start_time,$end_time"]);
        }

        if(!empty($shopIds)){
            array_push($map,['shop_id','in',$shopIds]);
        }

        if(!empty($shop_name)){
            $shopids = DB::name('shop')->where('shop_name','like',"%".$shop_name."%")->column('shop_id');
            if(!empty($shopids)){
                array_push($map,['shop_id','in',$shopids]);
            }
        }

        if(!empty($shop_id)){
            array_push($map,['shop_id','=',$shopIds]);
        }

        $count = CustomerPrestockExit::where($map)->count();


        if($count>0){
            $prestock_exit_log = CustomerPrestockExit::where($map)
                ->field('operator_id,deal_time,goods_id,type,is_cancel,cancel_time,cancel_operator_id,remark,customer_id,shop_id,num,shop_id')
                ->page($paging['page'], $paging['limit'])
                ->select()->toArray();

            $uid = array_column($prestock_exit_log,'customer_id');
            $shop_id = array_column($prestock_exit_log,'shop_id');
            $customer = DB::name('customer')->whereIn('id',$uid)->column('customer_name,telephone','id');
            $shop = DB::name('shop')->whereIn('shop_id',$shop_id)->column('shop_name','shop_id');

            $goods_name = DB::name('shop_goods')->where('id',$id)->value('name');
            foreach($prestock_exit_log as $k=>&$v){
                $v['goods_name'] = $goods_name;
                $v['customer_name'] = isset($customer[$v['customer_id']])?$customer[$v['customer_id']]['customer_name'] :'';
                $v['shop_name'] = isset($shop[$v['shop_id']]) ? $shop[$v['shop_id']]:'';
                $v['deal_times'] = !empty($v['deal_time']) ?date('Y-m-d',$v['deal_time']):'';
                $v['type'] = $v['type'] == 1?'出货':'退货';
            }
        }
        $data              = [];
        $data['list']      = $prestock_exit_log ?? [];
        $data['dataCount'] = $count ?? 0;
        return $data;
    }

    //商品预存记录导出
    public function preLogExport($param){

        $start_time = isset($param['start_time']) ? $param['start_time'] : '';
        $end_time = isset($param['end_time']) ? $param['end_time'] : '';
        $id = isset($param['id'])  ? intval($param['id']) : 0;
        $shopIds = isset($param['shopIds'])  ? $param['shopIds'] : '';

        $map=[
            ['b.goods_id','=',$id],
            ['a.status','=',2],
            ['b.prestock_type','=',2]
        ];

        if(!empty($start_time) && !empty($end_time)){
            $start_time = strtotime($start_time);
            $end_time = strtotime($end_time." 23:59:59");
            array_push($map,['a.deal_time','between',"$start_time,$end_time"]);
        }
        if(!empty($shopIds)){
            array_push($map,['a.shop_id','in',$shopIds]);
        }
        if(!empty($shop_id)){
            array_push($map,['a.shop_id','=',$shopIds]);
        }

        $shop_name = isset($param['shop_name']) && $param['shop_name'] ? trim($param['shop_name']) : ''; // 门店名称
        if(!empty($shop_name)){
            $shopids = DB::name('shop')->where('shop_name','like',"%".$shop_name."%")->column('shop_id');
            if(!empty($shopids)){
                array_push($map,['a.shop_id','in',$shopids]);
            }
        }

        $prestock_log = ShopOrderModel::alias('a')
            ->leftjoin('shop_order_goods b','a.id=b.order_id')
            ->where($map)->field('b.takeout_stock_num,b.goods_id,a.uid,a.shop_id,a.deal_time,b.id')
            ->select()->toArray();
        if(!empty($prestock_log)){
            $shop_order_goods_id = array_column($prestock_log,'id');
            $uid = array_column($prestock_log,'uid');
            $shop_id = array_column($prestock_log,'shopId');

            $customer = DB::name('customer')->whereIn('id',$uid)->column('customer_name,telephone','id');
            $shop = DB::name('shop')->whereIn('shop_id',$shop_id)->column('shop_name','shop_id');
            $prestock_goods_list = DB::name('customer_prestock_goods')->whereIn('order_goods_id',$shop_order_goods_id)->column('num','order_goods_id');
            $goods_name = DB::name('shop_goods')->where('id',$id)->value('name');
            foreach($prestock_log as $k=>&$v){
                $v['goods_name'] = $goods_name;
                $v['customer_name'] = isset($customer[$v['uid']])?$customer[$v['uid']]['customer_name'] :'';

                $v['shop_name'] = isset($shop[$v['shopId']]) ? $shop[$v['shopId']]:'';
                $v['prestock_num'] = isset($prestock_goods_list[$v['id']])?$prestock_goods_list[$v['id']]:0;
                $v['deal_times'] = date('Y-m-d',$v['dealTime']);
            }
        }
        $data              = [];
        $data['list']      = $prestock_log ?? [];
        return $data;
    }

    //商品预存记录导出
    public function preGoodsExport($param){

        $map = $where = [];

        $shopIds= $param['shopIds'] ?? '';
        if(!empty($shopIds)){
            array_push($map,  ['shop_id','in',$shopIds]);
            array_push($where,  ['a.shop_id','in',$shopIds]);
        }

        $shop_name = $param['shop_name'] ?? '';
        if(!empty($shop_name)){
            $shop_name_ids = DB::name('shop')->where('status',1)->where('shop_name','like',"%".$shop_name."%")->column('shop_id');
            array_push($map,['shop_id','in',$shop_name_ids]);
            array_push($where,  ['a.shop_id','in',$shop_name_ids]);
        }

        $goods_name = isset($param['goods_name'])  ? $param['goods_name'] : '';
        if(!empty($goods_name)){
            $goods_ids =ShopGoods::where('name','like','%'.$goods_name.'%')->column('id');
            array_push($map,['goods_id','in',$goods_ids]);
        }

        array_push($map,['is_cancel','=',0]);

        $list = CustomerPrestockGoods::where($map)
            ->field('sum(num) as num,goods_id')
            ->group('goods_id')
            ->having('num>0')
            ->select()->toArray(); //最后剩余次数
        if(!empty($list)){
            $goodsids =array_column($list,'goods_id');
            $goods = ShopGoods::whereIn('id',$goodsids)->column('name,kingdee_code','id');

            array_push($where,['prestock_type','=',2]);
            array_push($where,['b.goods_id','in',$goodsids]);
            array_push($where,['a.status','=',2]);
            $prestock_list = ShopOrderModel::alias('a')
                ->leftjoin('shop_order_goods b','a.id=b.order_id')
                ->where($where)->group('b.goods_id')->column('sum(b.takeout_stock_num) as num,b.goods_id','goods_id');

            foreach($list as $k=>&$v){
                $v['goods_name'] = isset($goods[$v['goods_id']]) ?$goods[$v['goods_id']]['name'] :"";
                $v['kingdee_code'] = isset($goods[$v['goods_id']]) ?$goods[$v['goods_id']]['kingdee_code'] :"";
                $v['prestock_num'] = isset($prestock_list[$v['goods_id']])?$prestock_list[$v['goods_id']]['num']:0; //预存总数
            }
        }

        $data              = [];
        $data['list']      = $list ?? [];
        return $data;
    }


}
